
-- 简单的伪随机数生成器（基于输入字符串）
local function simpleHash(str)
    local hash = 0
    for i = 1, #str do
        hash = (hash * 31 + string.byte(str, i)) % 2147483647
    end
    return hash
end

--固定随机数
function generateRandom(hash,min, max)
    if type(hash) ~= 'number' then
        hash = simpleHash(hash)
    end
    hash = (hash * 1103515245 + 9527) % 2147483647
    local ret = min + (hash % (max - min+1))
    return ret, hash
end

--权重伪随机数
function generateWeight(seed,tab)
	local obj
	if not tab or #tab == 0 then
		return obj
	end

	local pr_total = 0
	for _, v in ipairs(tab) do
		pr_total = pr_total + v[2]
	end

	if pr_total <= 0 then
		return obj
	end

	local random_num = generateRandom(seed,1, pr_total)
	local pr_hit = 0
	local index = 0
	for i, v in ipairs(tab) do
		if pr_hit <= random_num and random_num <= pr_hit + v[2] then
			index = i
			obj = v[1]
			break
		end
		pr_hit = pr_hit + v[2]
	end

	return obj, index
end

function randomGroup(name,count,min, max)
    local seed = simpleHash(name)
    local group = {}
    for i = 1, count do
        seed = (seed * 1103515245 + 9527) % 2147483647
        group[i] = seed
    end
    return group
end


-- 生成随机字符口令
-- 可用的字符集
local charset = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
function generatePassword(inputString,length)
    local length = length or 8  -- 默认长度为8
    if type(length) ~= "number" or length <= 0 then
        error("长度必须是一个正整数")
    end
    if not inputString or inputString == "" then
        inputString = "default"
    end
    
    local password = ""
    local seed = simpleHash(inputString)

    -- 生成指定长度的字符
    for i = 1, length do
        -- 使用种子和位置生成伪随机数
        seed = (seed * 1103515245 + 12345) % 2147483647
        local index = (seed % #charset) + 1
        password = password .. string.sub(charset, index, index)
    end
    
    return password
end

